package com.shaoshaohuo.app.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.adapter.WithdrawWayAdapter;
import com.shaoshaohuo.app.constant.ExtraName;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.CheckPayPwdEntity;
import com.shaoshaohuo.app.entity.PayAccount;
import com.shaoshaohuo.app.entity.PayAccountEntity;
import com.shaoshaohuo.app.entity.SupportWithdrawWay;
import com.shaoshaohuo.app.entity.SupportWithdrawWayEntity;
import com.shaoshaohuo.app.framework.SharedPreferencesHelper;
import com.shaoshaohuo.app.framework.SharedPreferencesHelper.Field;
import com.shaoshaohuo.app.net.HttpRequest;
import com.shaoshaohuo.app.net.HttpRequest.RequestListener;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.view.TopbarView;

import java.util.List;

/**
 * 
 * @author cao
 *
 */
public class WithdrawForAccountActivity extends BaseActivity implements OnClickListener {

	private TopbarView mTopbarView;

	private TextView mLeftMoneyText;

	private View mMoneyLayout;
	private View mCardTypeLayout;

	private EditText mMoneyEidt;
	private TextView mCardTypeText;
	private Button mAuthcodeButton;
	private EditText mAuthcodeNum;
	private Button mNextButton;

	private String freetotal;

	private String id,money,code;
	private PayAccount payAccount;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_withdraw_for_account);
		freetotal = getIntent().getStringExtra(ExtraName.freetotal);
		initView();
		setUpView();
		requestData();
	}

	private void requestData() {
			startLoadingDialog();
			RequestService.getInstance().payAccountList(this, true, PayAccountEntity.class, new HttpRequest.RequestListener() {
				@Override
				public void onSuccess(int requestCode, BaseEntity resultData) {
					dismissLoadingDialog();
					if (resultData.isOk()) {
						PayAccountEntity entity = (PayAccountEntity) resultData;
						if (entity.data != null && entity.data.list != null && entity.data.list.size() != 0) {
							payAccount = entity.data.list.get(0);
							setAccountView();
						}
					} else {
						showToast(resultData.getMsg());
					}
				}

				@Override
				public void onFailed(int requestCode, Exception error, String msg) {
					dismissLoadingDialog();
					showToast(R.string.please_check_network);
				}
			});

	}

	private void setAccountView(){
		if(payAccount==null)return;
		mCardTypeText.setText(payAccount.title + "(" + payAccount.account.substring(payAccount.account.length() - 4) + ")");
	}

	private void initView() {
		mTopbarView = (TopbarView) this.findViewById(R.id.topbar);

		mLeftMoneyText = (TextView) this.findViewById(R.id.textview_left_money);

		mMoneyLayout = this.findViewById(R.id.layout_money);
		mMoneyEidt = (EditText) this.findViewById(R.id.edittext_money);
		mCardTypeLayout = this.findViewById(R.id.layout_card_type);
		mCardTypeText = (TextView) this.findViewById(R.id.textview_card_type);
		mAuthcodeNum = (EditText) this.findViewById(R.id.edittext_authcode);
		mAuthcodeButton = (Button) this.findViewById(R.id.button_authcode);
		mNextButton = (Button) this.findViewById(R.id.button_next);
	}

	private void setUpView() {
		mTopbarView.setCenterText("提现");
		mTopbarView.setLeftView(true, true);

		mLeftMoneyText.setText("可提现金额:￥" + freetotal);

		mCardTypeLayout.setOnClickListener(this);
		mNextButton.setOnClickListener(this);
		mAuthcodeButton.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.layout_card_type:
			Intent intent = new Intent(this, PayAccountActivity.class);
			intent.putExtra(PayAccountActivity.getAccount, true);
			startActivityForResult(intent, 100);
			break;
		case R.id.button_authcode:
			getAuthcode();
			break;
		case R.id.button_next:

			money = mMoneyEidt.getText().toString().trim();

			if (TextUtils.isEmpty(money)) {
				showToast("请输入提现金额");
				return;
			}

			if (Double.parseDouble(money) < 10) {
				showToast("提现金额应大于10元");
				return;
			}
			if (Double.parseDouble(money) > 50000) {
				showToast("单笔提现金额不能超过5万");
				return;
			}
			if (Double.parseDouble(money) > Double.parseDouble(freetotal)) {
				showToast("可提现金额不足");
				return;
			}
			if (payAccount == null) {
				showToast("请选择收款账户");
				return;
			}

			id = payAccount.id;

			code = mAuthcodeNum.getText().toString().trim();
			if(TextUtils.isEmpty(code)){
				showToast("请输入验证码");
				return;
			}

			checkPayPwd();
			
			break;
		}
		
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK) {
			payAccount = (PayAccount) data.getSerializableExtra(ExtraName.account);
			setAccountView();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void showPwdDialog(CheckPayPwdEntity entity) {
		if ("1".equals(entity.getData().getIsset())) {
			withdrawForAccount();
		} else {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("未设置支付密码,请先设置支付密码");
			builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					Intent intent = new Intent(WithdrawForAccountActivity.this, PayManageActivity.class);
					startActivity(intent);
				}
			});
			builder.create().show();

		}
	}

	private void checkPayPwd() {
		startLoadingDialog();
		RequestService.getInstance().checkPayPwd(this, CheckPayPwdEntity.class, new RequestListener() {

			@Override
			public void onSuccess(int requestCode, BaseEntity resultData) {
				dismissLoadingDialog();
				if (resultData.isOk()) {
					CheckPayPwdEntity entity = (CheckPayPwdEntity) resultData;
					showPwdDialog(entity);
				} else {
					showToast(resultData.getMsg());
				}
			}

			@Override
			public void onFailed(int requestCode, Exception error, String msg) {
				dismissLoadingDialog();
				showToast(R.string.please_check_network);
			}
		});
	}

	private void withdrawForAccount(){
		startLoadingDialog();
		RequestService.getInstance().applyForAccount(this, id, money, code, BaseEntity.class, new RequestListener() {
			@Override
			public void onSuccess(int requestCode, BaseEntity resultData) {
				dismissLoadingDialog();
				if (resultData.isOk()) {
					showToast("提现申请提交成功");
					// 跳转到提现申请成功页面
					SharedPreferencesHelper.setString(Field.SHOW_BANK_NAME,
							payAccount.title);
					SharedPreferencesHelper.setString(Field.SHOW_BANK_ACCOUNT, payAccount.account);
					SharedPreferencesHelper.setString(Field.SHOW_BANK_MONEY, money);
					SharedPreferencesHelper.setString(Field.SHOW_BANK_ACCOUNT_NAME, payAccount.realname);
					startActivity(new Intent(getApplicationContext(), WithDrawEndingActivity.class));
					finish();
				} else {
					showToast(resultData.getMsg());
				}
			}

			@Override
			public void onFailed(int requestCode, Exception error, String msg) {
				dismissLoadingDialog();
				showToast(R.string.please_check_network);
			}
		});
	}



	private void getAuthcode() {

		startLoadingDialog();
		RequestService.getInstance().sendPaySms(this, BaseEntity.class, new RequestListener() {

			@Override
			public void onSuccess(int requestCode, BaseEntity resultData) {
				dismissLoadingDialog();
				if (resultData.isOk()) {
					mAuthcodeButton.setEnabled(false);
					mHandler.removeMessages(0);
					mHandler.sendMessageDelayed(mHandler.obtainMessage(0), 1 * 1000);
					showToast("验证码已发送");
				} else {
					showToast(resultData.getMsg());
				}
			}

			@Override
			public void onFailed(int requestCode, Exception error, String msg) {
				dismissLoadingDialog();
				showToast(R.string.please_check_network);
			}
		});
	}

	private static final int DEFAULT_SMS_VERIFYCODE_COUNTDOWN_TIME = 60;
	private int mUpdateCount = DEFAULT_SMS_VERIFYCODE_COUNTDOWN_TIME;
	private final Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 0) {
				--mUpdateCount;
				if (mUpdateCount > 0) {
					mAuthcodeButton.setText(String.format("重新发送(%d)", mUpdateCount));
					sendMessageDelayed(obtainMessage(0), 1 * 1000);
					mAuthcodeButton.setEnabled(false);
				} else {
					mAuthcodeButton.setText("重新发送");
					mUpdateCount = DEFAULT_SMS_VERIFYCODE_COUNTDOWN_TIME;
					mAuthcodeButton.setEnabled(true);
				}
			}
		}
	};

}
